# -*- coding: utf-8 -*-
# @日期 : 2022/1/28 0028
# @作者 : sean
# @版本 : v1.0
# @功能 :

from lxml import etree


parser = etree.HTMLParser(encoding = 'utf-8')
# 添加该参数可以避免 lxml.etree.XMLSyntaxError: Opening and ending tag mismatch
tree = etree.parse("htmlSample.html",parser = parser)

# 返回 ['百度','谷歌','搜狗']
result = tree.xpath("/html/body/ul/li/a/text()")
print(result)

# 返回第一个 百度 xpath索引从1开始
result = tree.xpath("/html/body/ul/li[1]/a/text()")
print(result)

# 查找 标签内容为大炮的a标签  [@属性=值]
result = tree.xpath("/html/body/ol/li/a[@href='dapao']/text()")
print(result)


#获取ol>li>a 标签属性
# 方法1
ol_li_list = tree.xpath("/html/body/ol/li")
for li in ol_li_list:
    result = li.xpath("./a/text()") # 在li中继续寻找
    print(result)
    result2 = li.xpath("./a/@href") # 在li中继续寻找a标签href属性值
    print(result2)
#获取ol>li>a 标签属性
# 方法2
print(tree.xpath("/html/body/ol/li/a/@href"))

# 如果html很长 我们没法从头往下一次写明标签
# 此时可以使用浏览器找到元素点击右键复制为xpath
print(tree.xpath("/html/body/div[1]/text()"))